#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-5 下午5:39
import mimetypes
import StringIO
from flask import Flask, url_for, render_template, Markup, request, make_response, redirect, abort, session, flash, \
    Response
from werkzeug.datastructures import Headers
from werkzeug.utils import secure_filename
import xlwt

app = Flask(__name__)
app.secret_key = "baotingfang"


@app.errorhandler(404)
def page_not_found_error(error):
    # 从这里可以看出是找不到什么页面
    print request.path
    return render_template("404.html", error=error.message), 404


@app.route("/500", methods=['GET'])
def internal_error():
    abort(500)


@app.errorhandler(500)
def error_500(error):
    response = make_response(render_template("500.html", error=error), 500)
    response.headers["X-Something"] = "error 505!"
    return response


@app.route("/")
# @app.route("/<name>")
def index(name=None):
    # 千万要记住是return
    return render_template("index.html", name="baotingfang")


@app.route("/mark_up")
def mark_up():
    # 返回的页面有hello world html的加粗效果
    # <blink>haha</blink> 原样输出
    return Markup("<strong>hello world %s</strong>") % '<blink>haha</blink>'


@app.route("/login", methods=["POST"])
def get_form_field():
    print request.form['username']
    print request.form['password']
    return 'POST DONE'


@app.route("/show", methods=['GET'])
def get_params():
    print request.args.get('param1')
    return 'GET DONE'


@app.route("/upload", methods=['POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file1']
        f.save("./upload/%s" % secure_filename(f.filename))
    return 'UPLOAD DONE'


@app.route("/mark_up_escape")
def mark_up_escape():
    # 会将大于号和小于号进行转义
    return Markup.escape('<blink>haha</blink>')


@app.route("/strip_tags")
def strip_tags():
    # 会将strong标签去掉
    return Markup("<strong>hello world %s</strong>").striptags()


@app.route("/static_url_test")
def download_static():
    return url_for("static", filename='dowload.txt')


@app.route("/store_cookie", methods=['GET'])
def store_cookie():
    response = make_response(render_template("store_cookie.html", info=":)"))
    response.set_cookie("username", "baotingfanghaha", path='/')
    return response


@app.route("/get_cookie", methods=["GET"])
def get_cookie():
    print request.cookies.get("username", "NO NAME")
    return "GET COOKIE :)"


@app.route("/redirect")
def redirect_page():
    print "redirect"
    # 跳转到/
    return redirect("/")


@app.route("/abort")
def abort_func():
    abort(404)


@app.route("/redirect1")
def redirect_page1():
    print "redirect1"
    # 跳转到index的方法的返回结果
    return redirect(url_for("index"))


@app.route("/save_session", methods=['GET'])
def save_session():
    print 'save session'
    session['user_name'] = 'baotingfang'
    return make_response("SAVE SESSION DONE")


@app.route("/get_session", methods=['GET'])
def get_session():
    print "get session"
    return make_response(session['user_name'])


@app.route("/remove_session", methods=['GET'])
def remove_session():
    print "clear session"
    session.pop("username", None)
    return 'REMOVE SESSION DONE'


@app.route("/clear_session", methods=['GET'])
def clear_session():
    print "clear session"
    session.clear()
    return 'CLEAR SESSION DONE'


@app.route("/flash", methods=['GET'])
def get_flash_message_page():
    flash("abc")
    flash("123  ")
    return render_template("flash.html")


@app.route("/export/")
def export_view():
    """
    显示了动态生成excel文件，返回给response流

    :return:
    """
    response = Response()
    response.status_code = 200

    workbook = xlwt.Workbook(encoding='utf-8')
    sheet = workbook.add_sheet("sheet1", cell_overwrite_ok=True)
    sheet.write(1, 1, u'测试')

    # 关键是下面这两行
    output = StringIO.StringIO()
    workbook.save(output)

    response.data = output.getvalue()

    file_name = 'data.xls'
    mimetype_tuple = mimetypes.guess_type(file_name)

    response_headers = Headers({
        'Pragma': "public",  # required,
        'Expires': '0',
        'Cache-Control': 'must-revalidate, post-check=0, pre-check=0,private',
        # 'Cache-Control': 'private',  # required for certain browsers,
        'Content-Type': mimetype_tuple[0],
        'Content-Disposition': 'attachment; filename=\"%s\";' % file_name,
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': len(response.data)
    })

    if not mimetype_tuple[1] is None:
        response_headers.update({
            'Content-Encoding': mimetype_tuple[1]
        })

    response.headers = response_headers
    response.set_cookie('fileDownload', 'true', path='/')

    return response


@app.route("/binary/")
def export_binary_file():
    """
    显示了读取一个二进制的文件，然后重定向到response流

    :return:
    """
    response = Response()
    response.status_code = 200

    f = open("app.py", 'rb')

    file_name = 'app.py'
    response.data = f.read()
    f.close()
    mimetype_tuple = mimetypes.guess_type(file_name)

    response_headers = Headers({
        'Pragma': "public",  # required,
        'Expires': '0',
        'Cache-Control': 'must-revalidate, post-check=0, pre-check=0,private',
        # 'Cache-Control': 'private',  # required for certain browsers,
        'Content-Type': mimetype_tuple[0],
        'Content-Disposition': 'attachment; filename=\"%s\";' % file_name,
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': len(response.data)
    })

    if not mimetype_tuple[1] is None:
        response_headers.update({
            'Content-Encoding': mimetype_tuple[1]
        })

    response.headers = response_headers
    response.set_cookie('fileDownload', 'true', path='/')

    return response

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)